<?php

namespace app\api\controller\v1;

use app\admin\model\BdOrg;
use app\admin\model\Intentionorderentry;
use app\admin\model\Inventory;
use app\admin\model\Inventoryentry;
use app\admin\model\Materialimage;
use app\admin\model\Surface;
use app\admin\model\Texture;
use app\common\model\Config;
use function GuzzleHttp\Promise\all;

class Customized extends Base
{
    public function getTexture()
    {
        $map = [];

        $keyword = !empty($this->params['fname']) ? trim($this->params['fname']) : '';

        if (!empty($keyword)) {
            $map['fname'] = ['like', '%' . $keyword . '%'];
        }
        $data = Texture::where('fenable', 1)
            ->whereIn('forgid', $this->forgids)
            ->where('fk_bdl_bd_datacenter', $this->datacenter)
            ->where($map)
            ->field('id,fname,fnumber,forgid,fk_bdl_bd_datacenter,fenable')
            ->order([
                'fname'=>'a-z',
                'fname'=>'0-9',
            ])
            ->select();

        $this->success('',$data);
    }
    public function getSurface()
    {
        $map = [];

        $keyword = !empty($this->params['fname']) ? trim($this->params['fname']) : '';

        if (!empty($keyword)) {
            $map['fname'] = ['like', '%' . $keyword . '%'];
        }

        $data = Surface::where('fenable', 1)
            ->whereIn('forgid', $this->forgids)
            ->where('fk_bdl_bd_datacenter', $this->datacenter)
            ->where($map)
            ->field('id,fname,fnumber,forgid,fk_bdl_bd_datacenter,fenable')
            ->order([
                'fname'=>'a-z',
                'fname'=>'0-9',
            ])
            ->select()

        ->each(function($a)
        {
            $img = Materialimage::where('fk_bdl_bd_surface',$a['id'])->find();
            $a['showImageUrl'] = !empty($img) ? $img['fk_bdl_imageurl'] :  $this->getDefaultImage();

        });

        $this->success('',$data);
    }

    public function getspecification()
    {
        $field      = $this->params['field'];

        $conifg     = Config::where('name',$field)->value('value');

        $conifg     = json_decode($conifg,true);
        $new_conifg = [];
        foreach ($conifg as $k=>$v)
        {
            $new_conifg[] = [
                'name'  => $v
            ];
        }

        $this->success('',$new_conifg);

    }

    public function addSub()
    {
        $check      = $this->plulicValidate($this->params,
            ['fk_bdl_bd_texture|定制材质', 'fk_bdl_bd_surface|定制表面', 'fk_bdl_bd_material_g|产品分组ID', 'guige|规格'],
            ['require',  'require',  'require',  'require']);

        if ($check['code'] == 1)
        {
            $this->error($check['msg']);
        }

        $dzOrder    = !empty($this->params['dzOrder']) ? $this->params['dzOrder'] : [];
        //不为空就是修改插入
        if(!empty($dzOrder))
        {
            //查询id
            $id       = \app\admin\model\Intentionorder::where('fk_bdl_wxbillno',$dzOrder)->find();
        }else{

            $forg       = BdOrg::get($this->forgid);
            $dzOrder    = makeMiNiOrderNo("WXDZ",$forg['fnumber']);

            $data       = [
                'forgid'                    => $this->forgid,
                'fk_bdl_bd_datacenter'      => $this->datacenter,
                'fk_bdl_userid'             => $this->user_id,
                'fk_bdl_bd_material_g'      => $this->params['fk_bdl_bd_material_g'],
                'fk_bdl_bd_customer'        => $this->customer_id,
                'fk_bdl_ordertype'          => 1,
                'fk_bdl_wxbillno'           => $dzOrder,
                'fenable'                   => 0
            ];
            //新增
            $id       = \app\admin\model\Intentionorder::create($data);
        }


        if($id)
        {
            $id             = $id->id;
            $guige          = json_decode(html_entity_decode($this->params['guige']),true);
            $new_guige      = [];

            foreach ($guige as $k=>$v)
            {
                $new_guige[] = [
                    'fk_bdl_qty'            => $v['fk_bdl_qty'],
                    'fk_bdl_refthickness'   => (float)$v['fk_bdl_refthickness'],
                    'fk_bdl_width'          => (int)$v['fk_bdl_width'],
                    'fk_bdl_length'         => (int)$v['fk_bdl_length'],
                    'fk_bdl_bd_texture'     => $this->params['fk_bdl_bd_texture'],
                    'fk_bdl_bd_surface'     => $this->params['fk_bdl_bd_surface'],
                    'id'                    => (int)$id
                ];
            }

            $res      = Intentionorderentry::insertAll($new_guige);
            //成功后 更新总数量
            $count    = Intentionorderentry::where('id',$id)->sum('fk_bdl_qty');
            \app\admin\model\Intentionorder::where('id',$id)->update(['fk_bdl_allqty'=>$count]);

            if($res)
            {
                $this->success('新增成功',[
                    'order' => $dzOrder,
                    'count' => Intentionorderentry::where('id',$id)->count()
                ]);
            }
        }


    }

    public function subList()
    {
        $check      = $this->plulicValidate($this->params,
            ['dzOrder|订单号'],
            ['require']);

        if ($check['code'] == 1)
        {
            $this->error($check['msg']);
        }

        $info       = \app\admin\model\Intentionorder::where('fk_bdl_wxbillno',$this->params['dzOrder'])->find();
        if(!$info)
        {
            $this->error('订单不存在');
        }


        $infos      = Intentionorderentry::where('id',$info['id'])
            ->order('id','desc')
            ->select()
            ->each(function($a){
                $a['fk_bdl_qty'] = floatval($a['fk_bdl_qty']);
            });

        // 准备一个数组来存储分组后的数据
        $groupedInfos = [];

        foreach ($infos as $infoson) {
            $fk_bdl_bd_surface = $infoson['fk_bdl_bd_surface'];

            if (!isset($groupedInfos[$fk_bdl_bd_surface])) {
                $groupedInfos[$fk_bdl_bd_surface] = [];
            }

            $groupedInfos[$fk_bdl_bd_surface][] = $infoson;
        }

        $new_data = [];
        foreach ($groupedInfos as $k=>$v)
        {
            $surface = $k;
            $surface = Surface::where('fname',$surface)
                ->where('forgid','in',$this->forgids)
                ->find();
            if(!empty($surface))
            {
                $surfaceI = Materialimage::where('fk_bdl_bd_surface',$surface['id'])
                    ->find();

                if(!empty($surfaceI))
                {
                    $showImageUrl = $surfaceI['fk_bdl_imageurl'];
                }else{
                    $showImageUrl = now_domain() . '/static/mini_program/waterDingzhi.png';
                }
            }else{
                $showImageUrl = now_domain() . '/static/mini_program/waterDingzhi.png';
            }

            $new_data[] = [
                'fk_bdl_bd_surface' => $k,
                'fk_bdl_bd_texture' =>$v[0]['fk_bdl_bd_texture'],
                'showImageUrl'      => $showImageUrl,
                'infos' => $v
            ];
        }




        $this->success('',[
            'data'  => $new_data,
            'order' => $this->params['dzOrder'],
            'count' => count($infos)
        ]);
    }
    public function update()
    {
        $type = $this->params['type'];
        switch ($type)
        {
            case 'del':
                $order = \app\admin\model\Intentionorder::where('fk_bdl_wxbillno',$this->params['order'])->find();

                if(!empty($order))
                {
                    $res = Intentionorderentry::where('id',$order['id'])->delete();
                }
                $this->subCount($order['id']);

                break;
            case 'delone':
                    $order = \app\admin\model\Intentionorderentry::where('fentryid',$this->params['id'])->find();
                    $res = Intentionorderentry::where('fentryid',$this->params['id'])->delete(true);

                    $this->subCount($order['id']);
                break;
            case 'delguige':

                $order = \app\admin\model\Intentionorder::where('fk_bdl_wxbillno',$this->params['order'])->find();

                if(!empty($order))
                {
                    $res = Intentionorderentry::where('id',$order['id'])
                        ->where('fk_bdl_bd_texture',$this->params['fk_bdl_bd_texture'])
                        ->where('fk_bdl_bd_surface',$this->params['fk_bdl_bd_surface'])
                        ->delete();
                }
                $this->subCount($order['id']);

                break;
            default:
                $res = Intentionorderentry::where('fentryid',$this->params['id'])->update([
                    'fk_bdl_qty'    => $this->params['count']
                ]);
                $this->subCount($this->params['id']);
                break;
        }

        if($res)
        {
            $this->success('操作成功');
        }

        $this->error('操作失败');
    }

    //确认产品  sublist顺序
    public function sub()
    {
        $check      = $this->plulicValidate($this->params,
            ['order|订单号', 'fk_bdl_bd_useraddress|发货地址'],
            ['require',  'require']);

        if ($check['code'] == 1)
        {
            $this->error($check['msg']);
        }
        $data = [
            'fk_bdl_bd_useraddress' => $this->params['fk_bdl_bd_useraddress'],
            'fenable'               =>1,
            'fk_bdl_ordertime'      => date('Y-m-d H:i:s'),
            'fk_bdl_userid'         => $this->user_id
        ];

        $fk_bdl_comment = !empty($this->params['fk_bdl_comment']) ? $this->params['fk_bdl_comment'] : [];

        if(!empty($fk_bdl_comment))
        {
            $data['fk_bdl_comment'] = $fk_bdl_comment;
        }


        $fk_bdl_image = !empty($this->params['fk_bdl_image']) ? $this->params['fk_bdl_image'] : [];

        if(!empty($fk_bdl_image))
        {
            $data['fk_bdl_image'] = $fk_bdl_image;
        }

        $res      = \app\admin\model\Intentionorder::where('fk_bdl_wxbillno',$this->params['order'])
            ->update($data);

        if($res)
        {
            $this->success('下单成功',[
                'order' => $this->params['order'],
            ]);
        }

        $this->error('下单失败,请稍后重试');

    }


    //计算总数
    public function subCount($id)
    {
        $sum = Intentionorderentry::where('id',$id)->sum('fk_bdl_qty');
        \app\admin\model\Intentionorder::where('id',$id)->update([
            'fk_bdl_allqty'     => $sum
        ]);

    }


}